import axios from 'axios'
import router from '../router'
import md5 from '@/utils/md5.js'
import {
  Toast
} from 'vant'

const service = axios.create({
  // 配置请求的根路径
  // baseURL: 'https://gzh.mr.xliz.cn/index/test/',
  timeout: 10000,
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8;',
    Accept: 'application/json'
  }
})

// 配置请求拦截器
service.interceptors.request.use(
  config => {
    let sign = 'yljq'
    let timestamp = Date.parse(new Date())
    if (window.localStorage.getItem('token')) {
      config.params.key = window.localStorage.getItem('token')
      config.params.timestamp = timestamp
      config.params = objKeySort(config.params)
      for (let i in config.params) {
        sign += (i + config.params[i])
      }
      sign += 'yljq'
      sign = md5(sign)
      config.params.sign = sign
    }
    // config.headers.Authorization = window.sessionStorage.getItem('token')
    // 在最后必须 return config
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 配置请求返回数据
service.interceptors.response.use(
  response => {
    const res = response.data
    // 成功返回数据
    if (res.code === 200) {
      return res.datas
    } else if (res.code === 201) {
      if (router.app._route.path != '/login') {
        window.localStorage.setItem('beforeLoginUrl', router.app._route.fullPath)
      }
      window.localStorage.removeItem('token')
      return router.push('/login')
    } else {
      // Toast(res.error || 'Error')
      return Promise.reject(res.error || 'Error')
    }
  },
  error => {
    Toast(error || 'Error')
    return Promise.reject(error)
  }
)

function objKeySort(obj) {
  let newkey = Object.keys(obj).sort()
  let newObj = {}
  for (let i = 0; i < newkey.length; i++) {
    newObj[newkey[i]] = obj[newkey[i]]
  }
  return newObj
}

export default service
